[grails] setting cookies when render type is "contentType: text/json"

Posted by Robin Jamieson on Stack Overflow See other posts from Stack Overflow or by Robin Jamieson
Published on 2010-02-03T06:11:48Z Indexed on 2010/05/13 20:04 UTC
Read the original article Hit count: 269

Filed under:
|

Is it possible to set cookies on response when the return render type is set as json?

I can set cookies on the response object when returning with a standard render type and later on, I'm able to get it back on the subsequent request. However, if I were to set the cookies while rendering the return values as json, I can't seem to get back the cookie on the next request object. What's happening here?

These two actions work as expected with 'basicForm' performing a regular form post to the action, 'withRegularSubmit', when the user clicks submit.

// first action set the cookie and second action yields the originally set cookie
def regularAction = {
  // using cookie plugin
  response.setCookie("username-regular", "regularCookieUser123",604800); 
  return render(view: "basicForm");
}

// called by form post
def withRegularSubmit = {
  def myCookie = request.getCookie("username-regular"); 
  // returns the value 'regularCookieUser123'
  return render(view: "resultView");
}

When I switch to setting the cookie just before returning from the response with json, I don't get the cookie back with the post.

The request starts by getting an html document that contains a form and when doc load event is fired, the following request is invoked via javascript with jQuery like this:

var someUrl = "http://localhost/jsonAction";
$.get(someUrl, function(jsonData) { // do some work with javascript}

The controller work:

// this action is called initially and returns an html doc with a form. 
def loadJsonForm = {
  return render(view: "jsonForm");
}

// called via javascript when the document load event is fired
def jsonAction = {
  response.setCookie("username-json", "jsonCookieUser456",604800); // using cookie plugin
  return render(contentType:'text/json') { 'pair'('myKey': "someValue") };
}

// called by form post
def withJsonSubmit = {
  def myCookie = request.getCookie("username-json"); 
  // got null value, expecting: jsonCookieUser456
  return render(view: "resultView");
}

The data is returned to the server as a result of the user pressing the 'submit' button and not through a script. Prior to the submit of both 'withRegularSubmit' and 'withJsonSubmit', I see the cookies stored in the browser (Firefox) so I know they reached the client.

© Stack Overflow or respective owner

Related posts about grails

Related posts about groovy